package com.xinchen.aiowaste.vm

import com.blankj.utilcode.util.GsonUtils
import com.maple.model.data.AioUserInfo
import com.maple.model.entity.aio.LoginEntity
import com.maple.model.resp.BaseResp
import com.maple.utils.manager.SingleLiveEvent
import com.maple.utils.store.AioDBHelper
import com.maple.utils.util.HttpRequestUtils
import com.maple.utils.util.LogUtils
import com.xinchen.aiowaste.base.BaseViewModel
import com.xinchen.aiowaste.model.repository.CommonRepository
import java.util.WeakHashMap

class AccountViewModel: BaseViewModel(){

    private val repository by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { CommonRepository() }

    val loginEvent: SingleLiveEvent<Any> = SingleLiveEvent()

    override fun isSuccess(resp: BaseResp): Boolean {
        return (super.isSuccess(resp) || resp.code == "417")
    }
    fun onLogin(account: String,password: String,isRememberPwd: Boolean,platform: Int) {
        HttpRequestUtils.clearAccessToken()
        launchOnlyResult(block = {
            val params: WeakHashMap<String, Any> = WeakHashMap()
            params.put("userName", account)
            params.put("password", password)
            params.put("platform", platform.toString())
            repository.login(params)
        }, success = {
            it.let { data ->
                LogUtils.logGGQ("登录：${data}")
                val entity = GsonUtils.fromJson(GsonUtils.toJson(data), LoginEntity::class.java)
                entity?.let { user ->
                    saveUserInfo(account,password,isRememberPwd,platform,user)
                }?:let {
                    LogUtils.logGGQ("==获取数据为空！！！===>>>")
                    defUI.onToast("登录失败！")
                }
            }
        })
    }

    private fun saveUserInfo(account: String,password: String,isRememberPwd: Boolean,platform: Int,user: LoginEntity) {

        LogUtils.logGGQ("===saveUserInfo===${user.data.userId}")

        val userData: LoginEntity.Data? = user.data


        val userInfo: AioUserInfo = AioUserInfo()

        if(userData != null) {
            userInfo.entId = userData.entId?:""
            userInfo.userId = userData.userId?:""
            userInfo.entName = userData.entName?:""
            userInfo.userName = userData.userName?:""
            userInfo.time = userData.time?:""
            userInfo.realName = userData.realName?:""
            userInfo.weightManualInput = userData.weightManualInput?:""
        }
        userInfo.token = ""
        userInfo.count = user.count

        AioDBHelper.saveLoginInfo(account,if(isRememberPwd) password else "",platform)
        if(AioDBHelper.saveUser(userInfo)) {
            loginEvent.call()
        }
    }

}